package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    // 员工登录
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        // 1.参数校验
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BusinessException("非法参数");
        }

        // 2.根据用户名查询数据库
        Employee employee = employeeMapper.getByUsername(username);

        // 3.业务校验
        // 3-1 用户是否存在
        if (employee==null) {
            throw new BusinessException("用户名不存在");
        }

        // 3-2 密码是否正确
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5,employee.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 3-3 账号是否被禁用
        if (employee.getStatus()== StatusConstant.DISABLE) {
            throw new BusinessException("此账号被禁用，请联系管理员");
        }

        // 4.登录成功，返回employee
        return employee;
    }
}
